<?php
/**
 * NuggetForm class. This is where all the Admin side forms are generated
 * Most of this code is from Page Manager extension by SirNot
 */
class NuggetForm extends PostBackControl
{
	var $NuggetSelect;
	var $NuggetName = '', $NuggetID = '', $NuggetHTML = '', $NuggetHideName = 0, $NuggetDescription = '', $NuggetPosition = '[Frozen]', $NuggetRoles = 0, $NuggetWeight = 0, $NuggetPages='';
	var $RoleCheckboxes = '', $PageCheckboxes = '';
	var $key = '', $value = '', $Alternate=0;

	function NuggetForm(&$Context)
	{
		global $NuggetObj;


		$this->ValidActions = array('NuggetList', 'Nugget', 'RemoveNugget','ProcessNugget', 'ProcessNuggetList',  'ProcessRemoveNugget');
		$this->Constructor($Context);

		if(in_array($this->PostBackAction, array('ProcessNugget', 'Nugget')) || !is_array($NuggetObj->Nugget))
		{
			//get the role data
			$RoleMng = $this->Context->ObjectFactory->NewContextObject($Context, 'RoleManager');
			$RoleData = $RoleMng->GetRoles();
			if($RoleData)
			{
				$NuggetObj->Roles[] = array('ID' => 0, 'Name' => $this->Context->GetDefinition('Unathenticated'));
				while($Row = $this->Context->Database->GetRow($RoleData))
				$NuggetObj->Roles[] = array('ID' => $Row['RoleID'], 'Name' => FormatStringForDisplay($Row['Name']));
			}
		}

		if($this->IsPostBack)
		{
			if($this->PostBackAction == 'ProcessNugget')
			{
				if(!$NuggetObj->CreateNugget($this))
				header('Location: '.$this->Context->Configuration['WEB_ROOT'].'settings.php?PostBackAction=NuggetList');
			}
			else if($this->PostBackAction == 'ProcessNuggetList')
			{
				if(!$NuggetObj->SaveNuggetList())
				header('Location: '.$this->Context->Configuration['WEB_ROOT'].'settings.php?PostBackAction=NuggetList');
			}
			else if($this->PostBackAction == 'ProcessRemoveNugget')
			{
				$NuggetObj->RemoveNugget();
				header('Location: '.$this->Context->Configuration['WEB_ROOT'].'settings.php?PostBackAction=NuggetList');
			}

			if(in_array($this->PostBackAction, array('Nugget', 'ProcessNugget', 'RemoveNugget')))
			{
				// Generate Nugget select fields.
				$this->NuggetSelect = $this->Context->ObjectFactory->NewObject($this->Context, 'Select');
				$this->NuggetSelect->Name = 'NuggetID';
				$this->NuggetSelect->CssClass = 'SmallInput';
				$this->NuggetSelect->Attributes .= 'id="nuggetselect"';
				for($i = 0; $i < count($NuggetObj->Nugget); $i++)
					$this->NuggetSelect->AddOption($NuggetObj->Nugget[$i]['id'], $NuggetObj->Nugget[$i]['name']);
				if($this->PostBackAction != 'RemoveNugget') $this->NuggetSelect->AddOption('', $this->Context->GetDefinition('[Create Nugget]'));
			}
			if(in_array($this->PostBackAction, array('NuggetList', 'ProcessNuggetList','Nugget', 'ProcessNugget')))
			{
				// Generate Weight select fields.
				$this->WeightSelect = $this->Context->ObjectFactory->NewObject($this->Context, 'Select');
				$this->WeightSelect->Name = 'Weight';
				$this->WeightSelect->CssClass = 'WeightSelect SmallInput';
				for($i = $NuggetObj->Weight['min']; $i <= $NuggetObj->Weight['max']; $i++)
					$this->WeightSelect->AddOption($i, $i);

				// Generate Position select fields.
				$this->PositionSelect = $this->Context->ObjectFactory->NewObject($this->Context, 'Select');
				$this->PositionSelect->Name = 'Position';
				$this->PositionSelect->CssClass = 'PositionSelect SmallInput';
				for($i = 0; $i < count($NuggetObj->Position); $i++)
					$this->PositionSelect->AddOption($NuggetObj->Position[$i]['position'], ($NuggetObj->Position[$i]['name']));
			}
		}
	}

	function Render()
	{
		global $NuggetObj;

		if($this->IsPostBack)
		{
			$this->PostBackParams->Clear();

			//editing or creating a nugget
			if($this->PostBackAction == 'Nugget' || $this->PostBackAction == 'ProcessNugget')
			{
				// Allow Page Manager pages and any other tabs which are not added by Vanilla
				global $Menu;
				reset($Menu->Tabs);
				while (list(,$Value) = each($Menu->Tabs))
				{
					if (!in_array($Value['Value'],array("settings","search","account","discussions","categories")))
					{
						$NuggetObj->Pages = array_merge($NuggetObj->Pages, array(array('name' => $Value['Text'], 'page' => $Value['Value'])));
					}
				}

				// Create RoleCheckboxes and PageCheckboxes
				$IsValid = isset($NuggetObj->Nugget[$GLOBALS['NuggetObj']->NuggetIndex]) || $this->PostBackAction == 'ProcessNugget';
				if($IsValid && $this->PostBackAction == 'Nugget')
				{
					$this->NuggetRoles = $NuggetObj->Nugget[$GLOBALS['NuggetObj']->NuggetIndex]['roles'];
					$this->NuggetPages = $NuggetObj->Nugget[$GLOBALS['NuggetObj']->NuggetIndex]['pages'];
				}

				for($i = 0; $i < count($NuggetObj->Roles); $i++)
				{
					$this->RoleCheckboxes .= "<li><p><span>".GetDynamicCheckBox("AllowedRoles[]", $NuggetObj->Roles[$i]['ID'],
					$IsValid ? in_array($NuggetObj->Roles[$i]['ID'], $this->NuggetRoles) : 1, "", $NuggetObj->Roles[$i]['Name'],
					'', 'RoleID_'.$NuggetObj->Roles[$i]['ID'])."</span></p></li>\r\n";
				}

				for($i = 0; $i < count($NuggetObj->Pages); $i++)
				{
					$this->PageCheckboxes .= "<li><p><span>".GetDynamicCheckBox("AllowedPages[]", $NuggetObj->Pages[$i]['page'],
					$IsValid ? in_array($NuggetObj->Pages[$i]['page'], $this->NuggetPages) : 1, "", $NuggetObj->Pages[$i]['name'],
					'', 'PageID_'.str_replace(" ","_",$NuggetObj->Pages[$i]['name']))."</span></p></li>\r\n";
				}

				if(isset($NuggetObj->Nugget[$GLOBALS['NuggetObj']->NuggetIndex]) && $this->PostBackAction == 'Nugget')
				{
					$this->NuggetName = htmlspecialchars($NuggetObj->Nugget[$GLOBALS['NuggetObj']->NuggetIndex]['name']);
					$this->NuggetID = (int)@$NuggetObj->Nugget[$GLOBALS['NuggetObj']->NuggetIndex]['id'];
					$this->NuggetHTML = htmlspecialchars($NuggetObj->Nugget[$GLOBALS['NuggetObj']->NuggetIndex]['html']);
					$this->NuggetHideName = (int)@$NuggetObj->Nugget[$GLOBALS['NuggetObj']->NuggetIndex]['hideName'];
					$this->NuggetDescription = htmlspecialchars($NuggetObj->Nugget[$GLOBALS['NuggetObj']->NuggetIndex]['description']);
					$this->NuggetPosition = htmlspecialchars($NuggetObj->Nugget[$GLOBALS['NuggetObj']->NuggetIndex]['position']);
					$this->NuggetWeight = (int)@$NuggetObj->Nugget[$GLOBALS['NuggetObj']->NuggetIndex]['weight'];
					$this->PositionSelect->SelectedValue = ($NuggetObj->Nugget[$GLOBALS['NuggetObj']->NuggetIndex]['position']);
					$this->WeightSelect->SelectedValue = (int)@$NuggetObj->Nugget[$GLOBALS['NuggetObj']->NuggetIndex]['weight'];

				}

				$this->PostBackParams->Set('PostBackAction', 'ProcessNugget');
				echo('<div id="Form" class="Account NuggetList RoleEditForm">
					<fieldset>
						<legend>'.$this->Context->GetDefinition("NuggetManagement").'</legend>');
				if(isset($NuggetObj->Nugget[$GLOBALS['NuggetObj']->NuggetIndex]))
				{
					$this->NuggetSelect->Attributes .= ' onchange="document.location=\'?PostBackAction=Nugget&NuggetID=\'+this.options[this.selectedIndex].value;"';
                                        $this->NuggetSelect->SelectedValue = $GLOBALS['NuggetObj']->SentNuggetID;

					echo('
						'.$this->Get_Warnings().'
						'.$this->Get_PostBackForm('frmNugget').'
						<h2>1. '.$this->Context->GetDefinition('SelectPage').'</h2>
						<ul><li>'.$this->NuggetSelect->Get().'</li></ul>
						<h2>2. '.$this->Context->GetDefinition('NuggetEdit').'</h2>');
				}
				else
				{
					echo('
						'.$this->Get_Warnings().'
						'.$this->Get_PostBackForm('frmNugget').'
						<h2>'.$this->Context->GetDefinition('DefineNewNugget').'</h2>');
				}

				echo('
					<ul>
						<li>
							<label for="txtNuggetName">'.$this->Context->GetDefinition('NuggetName').'</label>
							<input type="text" name="Name" value="'.$this->NuggetName.'" maxlength="80" class="SmallInput" id="txtNuggetName" />
						</li>
						<li>
							<p class="Description"><span>'.
							GetDynamicCheckBox('HideName', 1,$this->NuggetHideName,'',$this->Context->GetDefinition('NuggetNameHide')).
							'</span></p>
						</li>
						<li>
							<label for="txtNuggetDescription">'.$this->Context->GetDefinition('NuggetDescription').' <small>'.$this->Context->GetDefinition('(optional)').'</small></label>
							<input type="text" name="Description" value="'.$this->NuggetDescription.'" maxlength="80" class="SmallInput" id="txtNuggetDescription" />
							<p class="Description">'.$this->Context->GetDefinition('NuggetDescriptionNotes').'</p>
						</li>
						<li>
							<label for="Position">'.$this->Context->GetDefinition('NuggetPan').'</label>
							'.$this->PositionSelect->Get().'
						</li>
						<li>
							<label for="Weight">'.$this->Context->GetDefinition('NuggetWeight').'</label>
							'.$this->WeightSelect->Get().'
							<p class="Description">'.$this->Context->GetDefinition('NuggetWeightNotes').'</p>

						</li>
						<li>
							<input type="hidden" name="ID" value="'.$this->NuggetID.'" maxlength="80" class="SmallInput" id="txtNuggetID" />
							<label for="txtNuggetHTML">'.$this->Context->GetDefinition('NuggetHTML').'</label>
							<textarea name="HTML" id="txtNuggetHTML" rows=25>'.$this->NuggetHTML.'</textarea>
							<p class="Description">'.$this->Context->GetDefinition('NuggetHTMLNotes').'</p>
						</li>
							<table cellspacing="5">
							<tbody><tr><td>
								<p class="Description"><strong>'.$this->Context->GetDefinition('NuggetPages').'</strong><br />
								'.$this->Context->GetDefinition('NuggetPagesNotes').'</p>
							</td>
							<td>
								<p class="Description"><strong>'.$this->Context->GetDefinition('Roles').'</strong><br />
								'.$this->Context->GetDefinition('NuggetRoleNotes').'</p>
							</td></tr>
							<tr><td>Check: <a onclick="CheckAll(\'PageID_\'); return false;" href="./">All</a>, <a onclick="CheckNone(\'PageID_\'); return false;" href="./">None</a></td>
							<td>Check: <a onclick="CheckAll(\'RoleID_\'); return false;" href="./">All</a>, <a onclick="CheckNone(\'RoleID_\'); return false;" href="./">None</a></td>
							</tr>

							<tr><td valign="top" >
								'.$this->PageCheckboxes.'
							</td>
							<td valign="top">
								'.$this->RoleCheckboxes.'
							</td></tr></tbody></table>
						</ul>
					<div class="Submit">

						<input type="submit" name="btnSave" value="'.$this->Context->GetDefinition('Save').'" class="Button SubmitButton" />
						<a href="./settings.php?PostBackAction=NuggetList" class="CancelButton">'.$this->Context->GetDefinition('Cancel').'</a>
					</div>
					</form>
				</fieldset>
				</div>');
				}
			//removing a nugget
			else if($this->PostBackAction == 'RemoveNugget')
			{
				$this->PostBackParams->Set('PostBackAction', 'ProcessRemoveNugget');
				$this->NuggetSelect->Attributes .= ' onchange="document.location=\'?PostBackAction=RemoveNugget&NuggetID=\'+this.options[this.selectedIndex].value;"';
				$this->NuggetSelect->SelectedValue = $GLOBALS['NuggetObj']->SentNuggetID;
				$this->NuggetName = htmlspecialchars($NuggetObj->Nugget[$GLOBALS['NuggetObj']->NuggetIndex]['name']);

				echo('<div id="Form" class="Account RoleRemoveForm"><fieldset>
					<legend>'.$this->Context->GetDefinition('NuggetManagement').'</legend>
					'.$this->Get_PostBackForm('frmRemoveNugget').'

					<p><strong>Are you sure you want to trash "'.$this->NuggetName.'" nugget and not freeze it for later use.</strong></p><p> If you want to freeze it, select [Frozen] from the Pan select box</p>
					<ul><li>'.$this->NuggetSelect->Get().'</li></ul>
					<div class="Submit">
						<input type="submit" name="btnSave" value="'.$this->Context->GetDefinition('Trash it').'" class="Button SubmitButton RoleRemoveButton" />
						<a href="./settings.php?PostBackAction=NuggetList" class="CancelButton">'.$this->Context->GetDefinition('Cancel').'</a>
					</div>
					</form>
					</fieldset>
					</div>'
					);
			}
			//list them all
			else if($this->PostBackAction == 'NuggetList')
			{

				echo('<div id="Form" class="Account NuggetList">
					<fieldset>
						<legend>'.$this->Context->GetDefinition('NuggetManagement').'</legend>
						<form method="get" action="'.GetUrl($this->Context->Configuration, $this->Context->SelfUrl).'">
							<input type="hidden" name="PostBackAction" value="Nugget" />
							<p>'.$this->Context->GetDefinition('NuggetNotes').'</p>
							<p id="ReadDocumentation"><a href="#" onclick="document.getElementById(\'NuggetDocumentation\').style.display = \'block\';document.getElementById(\'ReadDocumentation\').style.display = \'none\';">Read Cooking Documentation</a></p>
							<div id="NuggetDocumentation" style="display:none">'.$this->Context->GetDefinition('NuggetDocumentation').'</div>
							<p><input type="submit" name="btnNewNugget" value="'.$this->Context->GetDefinition('CreateANewNugget').'" class="Button SubmitButton NewRoleButton" /></p>

						</form>

					</fieldset>
					</div>
				');

				if ($GLOBALS['NuggetObj']->Nugget) {
					$this->PostBackParams->Set('PostBackAction', 'ProcessNuggetList');
					echo('<div id="Form" class="Account NuggetList">
					     <fieldset>

						'.$this->Get_PostBackForm('frmNuggetList').'
						<table id="NuggetListTable">
							<thead>
								<tr>
									<th>Nugget</th>
									<th>Pan</th>
									<th>Weight</th>
									<th>Serving</th>
								</tr>
							</thead>
							<tbody>');
					$cooked = 0; $frozen = 0;

					for($i = 0; $i < count($NuggetObj->Nugget); $i++)
					{
						$this->NuggetName = htmlspecialchars($GLOBALS['NuggetObj']->Nugget[$i]['name']);
						$this->NuggetDescription = htmlspecialchars($GLOBALS['NuggetObj']->Nugget[$i]['description']);

						$this->PositionSelect->Name = $i.'[Position]';
						$this->PositionSelect->SelectedValue = ($GLOBALS['NuggetObj']->Nugget[$i]['position']);

						$this->WeightSelect->Name = $i.'[Weight]';
						$this->WeightSelect->SelectedValue = (int)@$GLOBALS['NuggetObj']->Nugget[$i]['weight'];
						$this->NuggetStatus = (int)@$GLOBALS['NuggetObj']->Nugget[$i]['status'];

						$this->Alternate = FlipBool($this->Alternate);
						($this->Alternate) ? $class='even': $class='odd';

						// Display the heading only once
						if ($this->NuggetStatus && !$cooked) {
							echo('<tr><td class="region" colspan="4">Cooked</td></tr>'); $cooked = 1;
						}
						else if (!$this->NuggetStatus && !$frozen) {
							echo('<tr><td class="region" colspan="4">Frozen</td></tr>'); $frozen = 1;
						}
						echo('<tr class='.$class.'>
					        <td class="name"><strong>'.$this->NuggetName.'</strong><br />'.$this->NuggetDescription.'</td>
						<td>'.$this->PositionSelect->Get().'</td>
						<td>'.$this->WeightSelect->Get().'</td>
						<td><a href="'.$this->Context->Configuration['WEB_ROOT'].'settings.php?PostBackAction=Nugget&NuggetID='.$GLOBALS['NuggetObj']->Nugget[$i]['id'].'">'.$this->Context->GetDefinition('Edit').'</a>
						| <a href="'.$this->Context->Configuration['WEB_ROOT'].'settings.php?PostBackAction=RemoveNugget&NuggetID='.$GLOBALS['NuggetObj']->Nugget[$i]['id'].'">Trash it</a></td>
						</tr>
					');
					}
					echo('</tbody></table>
					<div class="Submit">
						<input type="submit" name="btnSave" value="'.$this->Context->GetDefinition('Save Nuggets').'" class="Button SubmitButton" />
						<a href="'.GetUrl($this->Context->Configuration, $this->Context->SelfUrl).'" class="CancelButton">'.$this->Context->GetDefinition('Cancel').'</a>
					</div>
				</form>
				</fieldset>
				</div>');
				}
			}
		}
	}
}
?>